package com.itheima.web.filters;

import com.itheima.utils.CookieUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter("/*")
public class AuthorFilter implements Filter {

    private FilterConfig filterConfig;

    /**
     * 初始化方法，获取过滤器的配置对象
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request;
        HttpServletResponse response;

        request = (HttpServletRequest) req;
        response = (HttpServletResponse) resp;
        String autoLoginCookie = CookieUtils.getCookieValue(request, "autoLoginCookie");
        String url = request.getRequestURI();
        if (autoLoginCookie!=null ||url.endsWith(".css")
                || url.endsWith(".js")
                || url.endsWith(".png")
                || url.endsWith("/")
                || url.endsWith("/system/user")
                || url.endsWith(".jpg")
                || url.endsWith("index.jsp")
                || url.endsWith("/checkCode")
                || url.endsWith("user-back.jsp")
                || url.endsWith("unauthorized.html")
                || url.endsWith("login.jsp")) {
            chain.doFilter(request, response);
            return;
        }
        response.sendRedirect(request.getContextPath()+"/unauthorized.html");
    }

    @Override
    public void destroy() {
        //可以做一些清理操作
    }
}
